﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon.PAAPI.WCF;
using System.ServiceModel;
using System.Configuration;

namespace Amazon.PAAPI
{
    class AmazonHelper
    {
        public static Product BuildProduct(Amazon.PAAPI.Item item)
        {
            ItemAttributes att = item.ItemAttributes;
            if ( (att.ISBN == null && (att.EISBN == null || att.EISBN.Length == 0) && att.UPC == null) || (att.ListPrice == null))   return null;
            else
            {
                Product p = new Product();
                if (att.Author != null)
                {

                    if (att.Author.Length == 1)
                    {
                        p.authors = att.Author[0];
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string authorName in att.Author)
                        {
                            sb.Append(authorName);
                            sb.Append(Char.ConvertFromUtf32(14)); //separator
                        }
                        p.authors = sb.ToString(0, sb.Length - 1);
                    }

                }
                else if (att.Artist != null)
                {
                    if (att.Artist.Length == 1)
                    {
                        p.authors = att.Artist[0];
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string authorName in att.Artist)
                        {
                            sb.Append(authorName);
                            sb.Append(Char.ConvertFromUtf32(14)); //separator
                        }
                        p.authors = sb.ToString(0, sb.Length - 1);
                    }
                }
                
                   
                
                p.name = att.Title;
                p.imageLarge = item.LargeImage == null ? null : item.LargeImage.URL;
                p.imageMedium = item.MediumImage == null ? null : item.MediumImage.URL;
                p.imageSmall = item.SmallImage == null ? null : item.SmallImage.URL;
                p.imageSwatch = item.ImageSets == null ? null : item.ImageSets[0].SwatchImage.URL;
                p.brand = att.Publisher ?? att.Brand ?? att.Manufacturer;
                p.description = item.EditorialReviews == null ? null : item.EditorialReviews[0].Content;
                p.ISBN = att.ISBN ?? (att.EISBN != null ? att.EISBN[0] : null);
                p.categ_id = att.ISBN != null ? 4 : 12;
                p.UPC = att.UPC;
                p.linkAmazon = item.DetailPageURL;
                return p;
            }
        }
        public static ItemSearchRequest BuildItemSearchRequest(AmazonArgs args,int pageNo)
        {
            ItemSearchRequest req = new ItemSearchRequest();
            req.SearchIndex = args.Category.Name;
            req.BrowseNode = args.Category.BrowseNode;
            req.MinimumPrice = args.PriceSlice.MinPrice.ToString("G2");
            req.MaximumPrice = args.PriceSlice.MaxPrice.ToString("G2");
            req.ResponseGroup = new string[] { "Large" };
            req.ItemPage = pageNo.ToString();
            return req;
        }
        public static ItemSearchRequest BuildItemSearchRequest(AmazonCategory args, int pageNo)
        {
            ItemSearchRequest req = new ItemSearchRequest();
            req.SearchIndex = args.Name;
            req.BrowseNode = args.BrowseNode;
            req.ResponseGroup = new string[] { "Large" };
            req.ItemPage = pageNo.ToString();
            return req;
        }
        public static AWSECommerceServicePortTypeClient BuildAmazonClient()
        {
            BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;

            // Instantiate Amazon ProductAdvertisingAPI client
            AWSECommerceServicePortTypeClient amazonClient = new AWSECommerceServicePortTypeClient(binding,
    new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));

            
            amazonClient.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(ConfigurationManager.AppSettings["accessKeyId"], ConfigurationManager.AppSettings["secretKey"]));
            return amazonClient;
        }

        public static ItemSearch BuildItemSearch(ItemSearchRequest request)
        {
            ItemSearch itemSearch = new ItemSearch();
            itemSearch.Request = new ItemSearchRequest[] { request };
            itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["accessKeyId"];
            itemSearch.AssociateTag = ConfigurationManager.AppSettings["associateTag"];
            return itemSearch;
        }
        public static bool IsResponseValid(ItemSearchResponse response)
        {
            return (response != null && response.Items != null && response.Items[0] != null && response.Items[0].Request != null && (String.Compare("true", response.Items[0].Request.IsValid, true) == 0) && response.Items[0].Item != null);
        }
    }
}
